package log

import (
	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"io"
	"os"
	"path"
	"server/src/global"
	"time"
)

func InitLogger() {
	encoder := getEncoder()

	//两个interface,判断日志等级
	//warnlevel及以下归到info日志
	infoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl <= zapcore.WarnLevel
	})
	//warnlevel及以上归到warn日志
	warnLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl > zapcore.WarnLevel
	})

	//文件写入或者更新
	rootDir, _ := os.Getwd()
	infoWriter := getLogWriter(path.Join(rootDir, global.GVL_CFG.Zap.Dir), "info")
	warnWriter := getLogWriter(path.Join(rootDir, global.GVL_CFG.Zap.Dir), "fatal")

	//创建zap.Core,for logger
	//NewCore（输出日志的格式配置，）
	core := zapcore.NewTee(
		zapcore.NewCore(encoder, infoWriter, infoLevel),
		zapcore.NewCore(encoder, warnWriter, warnLevel),
	)
	//生成Logger
	logger := zap.New(core, zap.AddCaller())
	global.GVL_LOG = logger.Sugar()
}

// getEncoder
func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

// 得到LogWriter
func getLogWriter(filePath, filename string) zapcore.WriteSyncer {
	warnIoWriter := getWriter(filePath, filename)
	return zapcore.AddSync(warnIoWriter)
}

// 日志文件切割
func getWriter(filePath, filename string) io.Writer {
	// 保存日志30天，每24小时分割一次日志
	hook, err := rotatelogs.New(
		path.Join(filePath, "_%Y%m%d"+filename+".log"),
		//rotatelogs.WithLinkName(filePath),
		rotatelogs.WithMaxAge(time.Hour*24*30),
		rotatelogs.WithRotationTime(time.Hour*24),
	)
	if err != nil {
		panic(any(err))
	}
	return hook
}
